package com.atguigu.crud.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.atguigu.crud.bean.Employee;
import com.atguigu.crud.bean.Msg;
import com.atguigu.crud.service.EmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * 处理员工CRUD请求
 *
 * @author lfy
 */
@Controller
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    /**
     * ResponseBody需要正常工作需要导入json的包
     * @param pn
     * @return
     */
    /**
     * 支持jsr303校验，需要导入hibernate 包
     *
     * @param pn
     * @return
     */
    @RequestMapping("/emps")
    @ResponseBody
    public Msg getEmpsWithJson(@RequestParam(value = "pn", defaultValue = "1") Integer pn) {

        PageHelper.startPage(pn, 5);
        List<Employee> emps = employeeService.getAll();
//				使用pageinfo包装查询后的结果，只需要将pageinfo交给页面就可以
//		pageinfo里面封装了需要查询的数据       5是连续显示的页数
        PageInfo page = new PageInfo(emps, 5);
        //使用model将page传入到页面中
        return Msg.success().add("pageInfo", page);
    }

    /*
    获取所有员工

     */
//	@RequestMapping("/emps")
    public String getEmps(@RequestParam(value = "pn", defaultValue = "1") Integer pn, Model model) {
        //引入分页插件
        //在查询之前只需要调用
        //    页码		数量大小
        PageHelper.startPage(pn, 5);
        List<Employee> emps = employeeService.getAll();
//				使用pageinfo包装查询后的结果，只需要将pageinfo交给页面就可以
//		pageinfo里面封装了需要查询的数据       5是连续显示的页数
        PageInfo page = new PageInfo(emps, 5);
        //使用model将page传入到页面中
        model.addAttribute("pageInfo", page);


        return "list";
    }

    /**
     * 员工保存
     *
     * @return
     */
    @RequestMapping(value = "/emp", method = RequestMethod.POST)
    @ResponseBody
    public Msg saveEmp(@Valid Employee employee, BindingResult result) {
        Map<String,Object> map= new HashMap<>();
        if (result.hasErrors()) {
            List<FieldError> fieldErrors = result.getFieldErrors();
            for ( FieldError fieldError:fieldErrors) {
                System.out.println("错误的字段名"+fieldError.getField());
                System.out.println("错误信息"+fieldError.getDefaultMessage());
                map.put(fieldError.getField(), fieldError.getDefaultMessage());


            }

            return  Msg.fail().add("errorfields", map);
        } else {
            employeeService.saveEmp(employee);

            return Msg.success();
        }

    }


    //    检验用户名可用的方法
    @RequestMapping(value = "/checkUser")
    @ResponseBody
    public Msg checkUsername(@RequestParam("empName") String empName) {
//        先判断用户名是否是合法的表达式
        String regx = "(^[a-z0-9_-]{6,16}$)|(^[\\u2E80-\\u9FFF]{2,5})";
        boolean matches = empName.matches(regx);
        if (!matches) {
            return Msg.fail().add("va_msg", "用户名可以是2到5位的中文,或者6到16位的英文");
        }
//        数据库用户名校验
        boolean b = employeeService.checkUser(empName);
        if (b) {
            return Msg.success();
        } else {
            return Msg.fail().add("va_msg", "用户名不可用");
        }


    }
    @RequestMapping(value = "/emp/{empId}",method = RequestMethod.GET)
    @ResponseBody
    public Msg getEmp( Integer empId){
        Employee emp = employeeService.getEmp(empId);



        return Msg.success().add("emp", emp);
    }
}
